<template>
  <div class="device-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="140px">
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
          >
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import api from '@/api/apis/sceneRoom'
import { parseSceneData } from '@/utils/scene-data'

export default {
  name: 'AddDevice',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {},
      formList: [
        {
          name: '设备编码',
          prop: 'deviceCode',
          attrConfig: { placeholder: '请输入设备编码' }
        },
        {
          name: '设备名称',
          prop: 'deviceName',
          attrConfig: { placeholder: '请输入设备名称' }
        },
        {
          name: '设备类型',
          prop: 'deviceType',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'dictList',
          selectParams: {
            codeList: ['ecp-admin.device.deviceType']
          },
          attrConfig: {
            placeholder: '请选择设备类型',
            options: []
          },
          dataProp: {
            keyProp: 'ecp-admin.device.deviceType',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        },
        {
          name: '当前状态',
          prop: 'deviceStatus',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'dictList',
          selectParams: {
            codeList: ['ecp-admin.device.deviceStatus']
          },
          attrConfig: {
            placeholder: '请选择当前状态',
            options: []
          },
          dataProp: {
            keyProp: 'ecp-admin.device.deviceStatus',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        },
        {
          name: '是否重点关注设备',
          prop: 'isFocus',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'dictList',
          selectParams: {
            codeList: ['ecp-admin.device.isFocus']
          },
          attrConfig: {
            placeholder: '请选择是否重点关注设备',
            options: []
          },
          dataProp: {
            keyProp: 'ecp-admin.device.isFocus',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        },
        {
          name: '产品类型',
          prop: 'productTypeId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'ProductTypeSelected'
          },
          attrConfig: {
            placeholder: '请选择产品类型',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        },
        {
          name: '所属项目',
          prop: 'sceneProjectId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'SceneProjectSelected'
          },
          attrConfig: {
            placeholder: '请选择所属项目',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '所属场景',
          prop: 'sceneInfo',
          componentType: 'el-cascader',
          attrConfig: {
            placeholder: '请选择所属场景',
            props: { checkStrictly: true },
            options: []
          }
        },
        {
          name: '具体位置',
          prop: 'position',
          attrConfig: { placeholder: '请输入具体位置' }
        },
        { name: '' },
        {
          name: '备注',
          prop: 'remark',
          attrConfig: {
            type: 'textarea',
            placeholder: '请输入备注'
          }
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        deviceCode: [{ required: true, message: '请输入设备编码', trigger: 'blur' }],
        deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        deviceType: [{ required: true, message: '请选择设备类型', trigger: 'blur' }],
        deviceStatus: [{ required: true, message: '请选择当前状态', trigger: 'blur' }],
        isFocus: [{ required: true, message: '请选择是否重点设备', trigger: 'blur' }],
        productTypeId: [{ required: true, message: '请选择产品类型', trigger: 'blur' }],
        sceneProjectId: [{ required: true, message: '请选择所属项目', trigger: 'blur' }],
        sceneInfo: [{ required: false, message: '请选择所属场景', trigger: 'blur' }],
        remark: [{ max: 300, message: '最长支持300个字符', trigger: 'blur' }]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        this.$set(this.formData, 'id', data.id)

        if (data.sceneProjectId) {
          // 查询场景选择的数据
          this.getRoomList(data.sceneProjectId)
        }
        const sceneInfo = []
        if (data.sceneEdificeId) {
          sceneInfo.push(data.sceneEdificeId)
        }
        if (data.sceneFloorId) {
          sceneInfo.push(data.sceneFloorId)
        }
        if (data.sceneRoomId) {
          sceneInfo.push(data.sceneRoomId)
        }
        this.formData.sceneInfo = sceneInfo
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      const item = params.sceneInfo
      if (item) {
        if (item[0]) {
          params.sceneEdificeId = item[0]
        }
        if (item[1]) {
          params.sceneFloorId = item[1]
        }
        if (item[2]) {
          params.sceneRoomId = item[2]
        }
      }
      this.submit(params)
    }
  },
  methods: {
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
      if (config.prop === 'sceneProjectId') {
        // 选择项目后加载场景数据
        this.getRoomList(this.formData[config.prop])
      } else if (config.prop === 'deviceType' && this.formData.deviceType === '1') { //物联网设备
        if (this.formData.deviceCode != null && this.formData.deviceCode.length > 0) {
          this.$api.device.getDeviceStatus(this.formData.deviceCode).then((res) => {
            this.formData.deviceStatus = res.data
          })
        }
      }
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.device[
            this.isAdd ? 'add' : 'update'
            ](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'device-add')
          }
        }
      })
    },
    /**
     * 获取空间列表
     * @param sceneProjectId
     */
    async getRoomList(sceneProjectId) {
      const res = await api.queryRoomList({
        sceneProjectId,
        sortColumn: 'floorName',
        sortOrder: 'asc'
      })
      const roomList = parseSceneData(res.data)
      const item = this.formList[7]
      item.attrConfig.options = roomList
      this.$set(this.formList, 7, { ...item })
    }
  }
}
</script>

<style lang="scss" scoped>
.device-box {
  color: #333;
  padding: 0 20px;

  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      width: calc(50% - 10px);

      &.width100p {
        width: 100%;
      }

      .el-form-item__label {
        color: #666;
        font-size: 14px;
      }

      &.form-sub-title {
        width: 100%;

        .el-form-item__label {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          font-weight: bold;
          color: #333;
          font-size: 16px;
          line-height: 1;

          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 15px;
            background-color: #00858d;
            margin-right: 5px;
          }
        }
      }
    }

    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
